<?php
declare(strict_types=1);

namespace Modules\Base\Service;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Modules\Base\Models\BoxNumber;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class BoxService
{

    /**
     * @param $length 箱号个数
     * @param $from 箱号来源
     * @param int $docid 单据id
     * @param string $orgCode 组织/供应商代码
     * @param string $docno 单据编号
     * @param string $materialNo 物料编码/品号
     * @param bool $returnAll 是否返回原始插入内容
     * @return array
     */
    public static function makeBoxNumber($length,$from,$docid = 0,$orgCode = '',$docno = '',$materialNo = '',$returnAll = false,$boxType = 1){

        $boxModel = new BoxNumber();

        $todayCount = $boxModel->where('days',date('Ymd'))->count();

        $codeList = [];
        for($i = 1; $i <= $length; $i++ ){
            $todayCount++;

            $prefix = $boxType == 1 ? 'QW' : 'QWZZ';

            $code = $prefix . date('Ymd') . '-' . sprintf("%04d", $todayCount);

            $codeList[] = [
                'code'          => $code,
                'days'          => date('Ymd'),
                'from'          => $from,
                'docid'         => $docid,
                'org_code'      => $orgCode,
                'docno'         => $docno,
                'material_no'   => $materialNo,
                'box_type'      => $boxType,
                //'mix'           => $mix,
                'img'           => self::makeQrCodeImagePath($code),
                'creator_id'    => Auth::guard(getGuardName())->id(),
                'created_at'    => time()
            ];

        }
        $boxModel->insert($codeList);

        return $returnAll ? $codeList : array_column($codeList,'code');
    }


    /**
     * 箱号二维码保存
     * @param $qrcode
     * @return bool|false|string
     */
    static public function makeQrCodeImagePath($qrcode){
        //生成箱号二维码
        $qrImg = QrCode::format('png')->size(400)->generate($qrcode);
        $fileName = "{$qrcode}.png";
        $filePath = '/qrcode/' . $fileName;
        Storage::disk('qrcode')->put($fileName,$qrImg);
        return $filePath;
    }

}
